package utils

import (
	"strconv"
	"strings"
)

// 单位转换: G/g, M/m, K/k, B/b
func ConvertToSizeInt64(size string) (int64, error) {
	length := len(size)
	if length == 0 {
		return 0, nil
	}
	unit := strings.ToUpper(size[length-1:])
	if unit == "G" {
		return strToInt64(size[:len(size)-1], 1024*1024*1024)
	}
	if unit == "M" {
		return strToInt64(size[:len(size)-1], 1024*1024)
	}
	if unit == "K" {
		return strToInt64(size[:len(size)-1], 1024)
	}
	return strToInt64(size, 1)
}

func ConvertInt64(val string, defaultVal int64) int64 {
	if val == "" {
		return defaultVal
	}
	ret, err := strconv.ParseInt(val, 10, 64)
	if err != nil {
		return defaultVal
	}
	return ret
}

func strToInt64(str string, multiple int64) (int64, error) {
	i, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		return 0, err
	}
	return i * multiple, nil
}
